package utils;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;

public class AsyncJSONDownloader extends AsyncTask<String, Void, String> {

	Handler handler;
	public static int DOWNLOAD_COMPLETE = 10000;
	
	public AsyncJSONDownloader(Handler handler) {
		super();
		this.handler = handler;
	}

	@Override
	protected String doInBackground(String... urls) {
		for (String strUrl : urls) {
			try {
				URL url = new URL(strUrl);
				URLConnection connection = url.openConnection();
				HttpURLConnection urlConnection = (HttpURLConnection) connection;

				int responseCode = urlConnection.getResponseCode();

				if (responseCode == HttpURLConnection.HTTP_OK) {
					InputStream is = urlConnection.getInputStream();

					byte[] buffer = new byte[1024];
					int len = 0;
					ByteArrayOutputStream bos = new ByteArrayOutputStream();

					while ((len = is.read(buffer)) != -1) {
						bos.write(buffer, 0, len);
					}

					byte[] data = bos.toByteArray();

					String encodedStr = new String(data, "UTF-8");

					return encodedStr;

				}
			} catch (MalformedURLException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return null;
	}

	@Override
	protected void onPostExecute(String result) {
		Message mes = new Message();
		Bundle bundle = new Bundle();
		bundle.putString("response", result);
		mes.setData(bundle);
		mes.what = DOWNLOAD_COMPLETE;
		handler.sendMessage(mes);
	}
}
